#pragma once
#include "Protocol.hpp"
#include "log.hpp"

enum
{
    Div_Zero = 1,
    Mod_Zero,
    Other_Oper
};

class ServerCal
{
public:
    ServerCal()
    {

    }

    Response CalculatorHelper(const Request &req)
    {
        Response resp(-1,0);
        switch(req.GetOp())
        {
            case '+':
                resp.SetResult(req.GetX() + req.GetY());
                break;
            case '-':
                resp.SetResult(req.GetX() - req.GetY());
                break;
            case '*':
                resp.SetResult(req.GetX() * req.GetY());
                break;
            case '/':
                if(req.GetY() == 0)
                {
                    resp.SetCode(Div_Zero);
                }
                else
                {
                    resp.SetResult(req.GetX() / req.GetY());
                }
                break;
            case '%':
                if(req.GetY() == 0)
                {
                    resp.SetCode(Mod_Zero);
                }
                else
                {
                    resp.SetResult(req.GetX() % req.GetY());
                }
                break;
            default:
                std::cout<< "不支持的操作符: " << req.GetOp() << std::endl;
                resp.SetCode(Other_Oper);
                break;
        }
        return resp;
    }

    std::string Calculator(std::string &package)
    {
        std::string content;
        if(!Decode(package, content)) return "";
        Request req;
        if(!req.Deserialize(content)) return "";
        content.clear();
        std::cout<< "收到请求: " << req.GetX() << req.GetOp() << req.GetY() << "=?" << std::endl;
        Response resp = CalculatorHelper(req);
        resp.Serialize(content);
        content = Encode(content);
        return content;
    }

    ~ServerCal()
    {

    }
};